package org.racsor.cc.action;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.racsor.cc.model.PMF;
import org.racsor.cc.model.RequestCC;

import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class CallRequest extends HttpServlet {
    private static final Logger log = Logger.getLogger(CallRequest.class.getName());
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    String content = "application/x-amf";

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
	URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();

	try {
	    String id = (String) req.getParameter("id");
	    if (StringUtils.isEmpty(id)) {
		id = "4001";
	    }
	    log.warning("eo:id:" + id);

	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    RequestCC requestcc = pm.getObjectById(RequestCC.class, NumberUtils.createLong(id));

	    log.warning("url:" + requestcc.toString());

	    byte[] xurro = blobstoreService.fetchData(requestcc.getBlob(), 0, requestcc.getSize());

	    URL url = new URL(requestcc.getUrl() + "?" + requestcc.getParameters());

	    HTTPRequest reqredirect = new HTTPRequest(url, HTTPMethod.POST);
	    if (!StringUtils.isEmpty(requestcc.getCookies())) {
		reqredirect.setHeader(new HTTPHeader("Cookie", requestcc.getCookies()));
	    }
	    reqredirect.setHeader(new HTTPHeader("Connection", "keep-alive"));
	    reqredirect.setHeader(new HTTPHeader("Content-Type", content));
	    reqredirect.setPayload(xurro);

	    HTTPResponse fetchresp = fetcher.fetch(reqredirect);

	    log.warning("responsecode:" + fetchresp.getResponseCode());

	    List<HTTPHeader> headers = fetchresp.getHeaders();

	    for (HTTPHeader header : headers) {
		String headerName = header.getName();
		String headerValue = header.getValue();
		log.warning("headerName:" + headerName + ":headerValue:" + headerValue);
		if (StringUtils.startsWithIgnoreCase(headerName, "set-cookie")) {
		    log.warning("setCookie:" + headerValue);
		    requestcc.setCookies(headerValue);
		    try {
			pm.makePersistent(requestcc);
		    } finally {
			pm.close();
		    }
		}
	    }

	    log.warning("content:" + new String(fetchresp.getContent()));
	    RequestDispatcher dispatcher = req.getRequestDispatcher("WEB-INF/jsp/requestcc.jsp");
	    dispatcher.forward(req, resp);
	} catch (Exception e) {
	    log.warning(ExceptionUtils.getStackTrace(e));
	}

    }

    public void doGet_(HttpServletRequest req, HttpServletResponse resp) {

	try {
	    String id = (String) req.getParameter("id");
	    log.warning("id:" + id);

	    UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();

	    Date date = new Date();

	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    RequestCC requestcc = pm.getObjectById(RequestCC.class, NumberUtils.createLong(id));

	    log.warning(requestcc.toString());

	    byte[] xurro = blobstoreService.fetchData(requestcc.getBlob(), 0, requestcc.getSize());
	    String pet = new String(xurro);

	    //	    log.warning(pet);

	    HttpURLConnection connection = null;

	    //Create connection
	    URL url = new URL(requestcc.getUrl() + "?" + requestcc.getParameters());
	    log.warning("url:" + requestcc.getUrl() + "?" + requestcc.getParameters());
	    log.warning("Content-Length:" + requestcc.getSize());

	    connection = (HttpURLConnection) url.openConnection();
	    connection.setRequestMethod("POST");
	    connection.setRequestProperty("Connection", "keep-alive");
	    connection.setRequestProperty("Content-Type", content);
	    //	    connection.setRequestProperty("Content-Length", "" + xurro.length);

	    //	    connection.setUseCaches(false);
	    connection.setDoInput(true);
	    connection.setDoOutput(true);

	    //Send request
	    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	    wr.write(xurro);
	    wr.flush();
	    wr.close();

	    log.warning("responsecode:" + connection.getResponseCode());

	    //Get Response	
	    InputStream is = connection.getInputStream();
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    String line;
	    StringBuffer response = new StringBuffer();
	    while ((line = rd.readLine()) != null) {
		response.append(line);
		response.append('\r');
	    }
	    rd.close();
	    log.warning("response:" + response.toString());

	    RequestDispatcher dispatcher = req.getRequestDispatcher("WEB-INF/jsp/requestcc.jsp");
	    dispatcher.forward(req, resp);

	} catch (Exception e) {
	    log.warning(ExceptionUtils.getStackTrace(e));
	}

    }
}
